﻿Imports System.Net
Imports System.IO
Imports Newtonsoft.Json
Imports Library

Namespace HomeApps

    <AllowAnonymous()>
    Public Class OAuthController
        Inherits System.Web.Mvc.Controller

        Public Function Login(ByVal returnMessage As String) As ActionResult
            ViewBag.message = returnMessage
            Return View()
        End Function

        <HttpPost()>
        Public Function Login(ByVal userName As String, ByVal password As String) As ActionResult
            If SharedCalls.Authorize(userName, password) Then
                FormsAuthentication.SetAuthCookie(userName, True)
                Return RedirectToAction("Index", "AccountPeriod")
            Else
                Return View("Invalid UserID and Password")
            End If
        End Function

        Public Function googlelogin() As ActionResult
            Dim url = "https://accounts.google.com/o/oauth2/auth?" & "scope={0}&state={1}&redirect_uri={2}&response_type=code&client_id={3}&approval_prompt=force"
            'userinfo.email表示获取用户的email
            Dim scope = HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email")
            '对应于userinfo.email
            Dim state = "email"
            Dim redirecturi = HttpUtility.UrlEncode(ThisApplication.redirecturi)
            Dim cilentid = HttpUtility.UrlEncode(ThisApplication.ClientID)
            Return Redirect(String.Format(url, scope, state, redirecturi, cilentid))
        End Function

        Public Function googlecallback() As ActionResult
            '由于是https，这里必须要转换为httpwebrequest
            Dim webrequest__1 = TryCast(WebRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
            webrequest__1.Method = "post"
            webrequest__1.ContentType = "application/x-www-form-urlencoded"

            '参考https://developers.google.com/accounts/docs/oauth2webserver
            Dim postdata = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}" & "&grant_type=authorization_code",
                                         Request.QueryString("code"),
                                         ThisApplication.ClientID,
                                         ThisApplication.ClientSecret,
                                         ThisApplication.RedirectURI)

            '在http post请求中传递参数
            Using sw = New StreamWriter(webrequest__1.GetRequestStream())
                sw.Write(postdata)
            End Using

            '发送请求，并获取服务器响应
            Dim resonsejson = ""
            Using response = webrequest__1.GetResponse()
                Using sr = New StreamReader(response.GetResponseStream())
                    resonsejson = sr.ReadToEnd()
                End Using
            End Using

            '通过json.net对服务器返回的json字符串进行反序列化，得到access_token
            Dim accesstoken = JsonConvert.DeserializeAnonymousType(resonsejson, New With { _
             Key .access_token = "" _
            }).access_token

            Dim tempUrl As String = String.Format("https://www.googleapis.com/oauth2/v1/userinfo?access_token={0}", accesstoken.ToString())
            webrequest__1 = TryCast(WebRequest.Create(tempUrl), HttpWebRequest)
            webrequest__1.Method = "get"
            'webrequest__1.Headers.Add("authorization", "bearer " & Convert.ToString(accesstoken))

            Using response = webrequest__1.GetResponse()
                Using sr = New StreamReader(response.GetResponseStream())
                    Dim email As String = JsonConvert.DeserializeAnonymousType(sr.ReadToEnd(), New With {Key .email = ""}).email
                    FormsAuthentication.SetAuthCookie(email, True)
                    Return RedirectToAction("Index", "AccountPeriod")
                End Using
            End Using
        End Function

    End Class
End Namespace
